<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <button id="button">Load posts</button>
        <script src="../../dist/json-graphql-server.umd.cjs"></script>
        <script type="text/javascript">
            window.addEventListener('load', function() {
                const data = {
                    "posts": [
                        {
                            "id": 1,
                            "title": "Lorem Ipsum",
                            "views": 254,
                            "user_id": 123,
                        },
                        {
                            "id": 2,
                            "title": "Sic Dolor amet",
                            "views": 65,
                            "user_id": 456,
                        },
                    ],
                    "users": [
                        {
                            "id": 123,
                            "name": "John Doe"
                        },
                        {
                            "id": 456,
                            "name": "Jane Doe"
                        }
                    ],
                };

                const server = JsonGraphqlServer({
                    data,
                    url: 'http://localhost:3000/graphql'
                });

                server.start();
            });
            window.document.getElementById('button').addEventListener('click', function () {            
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "http://localhost:3000/graphql", true);
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.setRequestHeader("Accept", "application/json");
                xhr.onerror = function(error) {
                    console.error(error);
                }
                xhr.onload = function() {
                    const result = JSON.parse(xhr.responseText);
                    console.log('data returned:', result);
                    alert('Found ' + result.data.allPosts.length + ' posts');
                }
                const body = JSON.stringify({ query: 'query allPosts { allPosts { id } }' });
                xhr.send(body);
            });
        </script>
    </body>
</html>
